package com.jt.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 基于此controller测试是否启用本地缓存的配置
 * */
@RefreshScope
@RestController
public class ProviderCacheController {
    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @RequestMapping("/provider/cache01")
    public String doUseLocalCache01(){
        return "useLocalCache'value is   " + useLocalCache;
    }

    //----------------------------------------------------------------------------
    //构建一个本地（Local）缓存对象（基于jvm中的一个对象存储从数据库获取数据）
    private List<String> cache = new CopyOnWriteArrayList<>();

    @RequestMapping("/provider/cache02")
    public List<String> doUseLocalCache02(){
        if (!useLocalCache){
            System.out.println("====Get data from databases====");
            return Arrays.asList("Category-A", "Category-B", "Category-C");
        }
        if (cache.isEmpty()){
            synchronized (cache){
                if (cache.isEmpty()) {
                    System.out.println("====Get data from databases====");
                    //假设这部分分类信息是从数据库获取的，但是我不希望每次获取这部分常见信息都要从数据库获取===>本地缓存
                    List<String> cates = Arrays.asList("Category-A", "Category-B", "Category-C");
                    cache.addAll(cates);
                }
            }
        }
        return cache;
    }

}
